package com.itheima.shop.web.servlet;

import com.itheima.shop.entity.Category;
import com.itheima.shop.entity.PageBean;
import com.itheima.shop.entity.Product;
import com.itheima.shop.service.ProductService;
import com.itheima.shop.util.JsonUtil;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.converters.DateConverter;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.*;

/**
 * 商品模块-web层
 */
@WebServlet(name = "ProductServlet", value = "/ProductServlet")
public class ProductServlet extends BaseServlet {
    /**
     * 查询所有商品,输出pageBeanJSON,分页查询
     */
    protected void findAllProductAjax(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            int currPageNO = Integer.parseInt(request.getParameter("page"));
            int perPageNO = Integer.parseInt(request.getParameter("rows"));

            ProductService service = new ProductService();
            PageBean<Product> pageBean = service.findAllProductAjax(currPageNO, perPageNO);
            Map<String, Object> json = new HashMap<>();
            json.put("total", pageBean.getAllRecordNO());
            json.put("rows", pageBean.getList());
            JsonUtil.writeJson(response, json);
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("message", "商品查询失败!");
            System.out.println("错误");
            request.getRequestDispatcher("/message.jsp").forward(request,response);
        }
    }

    /**
     * 更新商品
     */
    private void updateProduct(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            Product product = upload(request, response);
            ProductService service = new ProductService();
            if (service.updateProduct(product)) {
                String result = "{\"success\":true}";
                JsonUtil.writeString(response, result);

            } else {
                String result = "{\"errorMsg\":出错了}";
                JsonUtil.writeString(response, result);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 新增商品
     */
    private void addProduct(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            Product product = upload(request, response);
            ProductService service = new ProductService();
            if (service.addProduct(product)) {
                String result = "{\"success\":true}";
                JsonUtil.writeString(response, result);

            } else {
                String result = "{\"errorMsg\":出错了}";
                JsonUtil.writeString(response, result);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除商品
     */
    private void deleteProduct(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            int pid = Integer.parseInt(request.getParameter("pid"));
            ProductService service = new ProductService();
            if (service.deleteProduct(pid)) {
                String result = "{\"success\":true}";
                JsonUtil.writeString(response, result);

            } else {
                String result = "{\"errorMsg\":出错了}";
                JsonUtil.writeString(response, result);
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }

    }

    /**
     * 获取前端上传的参数,包括文件
     */
    private Product upload(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Product product = new Product();
        Category category = new Category();
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        if (isMultipart == true) {
            Map<String, String> parameters = new HashMap<>();
            //Map<String, FileItem> files = new HashMap<>();
            String fileName = null;

            String encoding = "UTF-8";
            long sizeMax = -1;//图片最大上限
            int sizeThreshold = DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD;//5*1024 最大缓存
            String absoluteDir = this.getServletContext().getRealPath("/");
            String repositoryPath = absoluteDir + "imgTmp/";// 临时文件目录
            String uploadDir = absoluteDir + "products/1/";// 上传文件的目录
            DiskFileItemFactory factory = new DiskFileItemFactory();
            factory.setSizeThreshold(sizeThreshold);    //设置内存缓冲区的阀值
            factory.setRepository(new File(repositoryPath));
            //临时目录，默认
            ServletFileUpload upload = new ServletFileUpload(factory);
            upload.setHeaderEncoding(encoding);
            upload.setSizeMax(sizeMax);

            List<FileItem> items = upload.parseRequest(request);
            Iterator<FileItem> iter = items.iterator();

            while (iter.hasNext()) {
                FileItem item = iter.next();
                if (item.isFormField()) {
                    parameters.put(item.getFieldName(), item.getString(encoding));

                } else {
                    //files.put(item.getFieldName(),item);
                    fileName = item.getName();
                    File file = new File(uploadDir + item.getName());
                    item.write(file);
                }
            }
            //BeanUtils的转换器
            DateConverter dateConverter = new DateConverter(null);
            dateConverter.setPatterns(new String[]{"yyyy-MM-dd", "yyyy/MM/dd"});
            ConvertUtils.register(dateConverter, Date.class);

            BeanUtils.populate(product, parameters);
            BeanUtils.populate(category, parameters);
            String id = request.getParameter("pid");
            if (id != null) {
                product.setPid(Integer.parseInt(id));
            }
            product.setPimage("products/1/" + fileName);
            product.setCategory(category);
        }
        return product;
    }
}
